/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/DB/SqlConnection.h"
#include "Shared/DB/SqlPreparedStatement.h"
#include "Shared/DB/Database.h"


namespace Shared {
namespace DB {

    SqlConnection::SqlConnection(Database& db)
        : _error(false)
        , _errCode(0)
        , _errString("")
        , _db(db)
        , _lock()

        , _stmtHolder()
    {

    }

    SqlConnection::~SqlConnection(void)
    {
        if (_stmtHolder.size() > 0) {
            for (StmtHolder::size_type x = 0; 
                x < _stmtHolder.size(); ++x) {
                    if (_stmtHolder[x] != NULL) {
                        delete _stmtHolder[x];
                        _stmtHolder[x] = NULL;
                    }
            }
        }
    }

    SqlPreparedStatement* SqlConnection::createStatement(const std::string& fmt)
    {
        return new SqlPlainPreparedStatement(fmt, *this);
    }

    SqlPreparedStatement* SqlConnection::getStmt(std::uint32_t index)
    {
        if (_stmtHolder.size() <= index)
        { _stmtHolder.resize(index + 1, NULL); }

        SqlPreparedStatement* pStmt = NULL;

        if (_stmtHolder[index] == NULL)
        {
            std::string fmt = _db.getStmtString(index);
            SHARED_ASSERT(fmt.length());
            pStmt = createStatement(fmt);
            if (!pStmt->prepare())
            {
                SHARED_ASSERT(false && "Unable to prepare SQL statement");
                return NULL;
            }

            _stmtHolder[index] = pStmt;
        }
        else
        { pStmt = _stmtHolder[index]; }

        return pStmt;
    }

    bool SqlConnection::executeStmt(int index, const SqlStmtParameters& id)
    {
        if (index == -1)
        { return false; }

        SqlPreparedStatement* pStmt = getStmt(index);
        pStmt->bind(id);
        return pStmt->execute();
    }

}}